<template>
    <div class="app-container">
        <el-form :inline="true" :model="queryParams" label-width="68px" ref="queryForm" size="small"
                 style="text-align: left" v-show="showSearch">
            <el-form-item label="用户名称" prop="userName">
                <el-input
                        @keyup.enter.native="handleQuery"
                        clearable
                        size="medium"
                        placeholder="请输入用户名称"
                        v-model="queryParams.userName"
                />
            </el-form-item>
            <el-form-item label="手机号码" prop="userPhone">
                <el-input
                        @keyup.enter.native="handleQuery"
                        clearable
                        size="medium"
                        placeholder="请输入手机号码"
                        v-model="queryParams.userPhone"
                />
            </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery" icon="Search" size="mini" type="warning">搜索</el-button>
                <el-button @click="resetQuery" icon="Refresh" size="mini">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        @click="importButton"
                ><el-icon><Pointer /></el-icon>导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        @click="handleExport"
                ><el-icon><Download /></el-icon>导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        :disabled="multiple"
                        @click="handleDelete"
                        plain
                        type="danger"
                ><el-icon><Delete /></el-icon>删除
                </el-button>
            </el-col>
        </el-row>

        <el-table :data="userList" @selection-change="handleSelectionChange" row-key="id" v-loading="loading" style="margin-top: 10px">
            <el-table-column :reserve-selection="true" align="center" type="selection" width="50"/>
            <el-table-column align="center" label="头像" prop="avatar" width="120">
                <template #default="scope">
                    <el-image
                            :src="scope.row.avatar"
                            style="width: 80px; height: 80px;border-radius: 10px;"></el-image>
                </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" align="center" label="用户昵称" prop="userName"/>
            <el-table-column align="center" label="手机号(账号)" prop="userPhone"/>
            <el-table-column align="center" label="角色" prop="userRole">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.userRole=='A'">管理员</el-tag>
                    <el-tag type="warning" v-else>普通用户</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime">
                <template #default="scope">
                    <span>{{ $filters.formatDate(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    class-name="small-padding fixed-width"
                    label="操作"
                    width="160"
            >
                <template #default="scope">
                    <el-button
                            @click="handleUpdate(scope.row)"
                            icon="Edit"
                            size="mini"
                            type="text"
                    >修改
                    </el-button>
                    <el-button
                            @click="handleDelete(scope.row)"
                            icon="Delete"
                            size="mini"
                            type="text"
                    >删除
                    </el-button>
                    <el-dropdown @command="(command) => handleCommand(command, scope.row)" size="mini">
                        <el-button icon="More" size="mini" type="text">更多</el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="handleResetPwd" icon="Key">重置密码</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <template v-if="userList.length!=0">
            <el-pagination
                    :page-sizes="[5, 10, 15, 20]"
                    :total="total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper"
                    v-model:current-page="queryParams.pageNum"
                    v-model:page-size="queryParams.pageSize"
            />
        </template>

        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" v-model="dialogFormVisible" width="30%">
            <el-form :model="form" :rules="rules" ref="ruleFormRef">
                <el-row>
                    <el-col :span="15">
                        <el-form-item label="昵称" prop="userName">
                            <el-input maxlength="30" placeholder="请填写用户名称" v-model="form.userName"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                  <el-col :span="15">
                    <el-form-item label="手机" prop="userPhone">
                      <el-input maxlength="11" placeholder="请填写手机号码" v-model="form.userPhone"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row style="padding-left: 10px">
                    <el-col :span="16">
                        <el-form-item label="角色">
                            <el-select placeholder="请选择角色" v-model="form.userRole">
                                <el-option
                                        :label="role.label"
                                        :value="role.value"
                                        v-for="role in roleOptions"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row style="padding-left: 10px">
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio key="0" label="0">启用</el-radio>
                                <el-radio key="1" label="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row style="padding-left: 10px">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input placeholder="请输入内容" type="textarea" v-model="form.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel()">取消</el-button>
                <el-button @click="submitForm()" type="primary">
                  确定
                </el-button>
              </span>
            </template>
        </el-dialog>
        <el-dialog title="用户导入" v-model="importUser" width="30%">
            <el-upload
                    class="upload-demo"
                    :action="importUrl"
                    :on-change="handleChange"
                    :on-success="handleSuccess"
                    :before-upload="handleBefore"
                    :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且不超过500kb</div>
            </el-upload>
        </el-dialog>

    </div>
</template>

<script>

    export default {
        name: "User",
        data() {
            return {
                fileList: [],
                importUrl:"http://127.0.0.1:8086/user/import",
                importUser:false,
                dialogFormVisible:false,
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 用户表格数据
                userList: [],
                // 弹出层标题
                title: "",
                // 表单参数
                form: {},
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 5,
                    userName: '',
                    userPhone: '',
                },
                roleOptions:[
                    {
                        label:"普通用户",
                        value:"U",
                    },
                    {
                        label:"管理员",
                        value: "A",
                    }
                ],
                // 表单校验
                rules: {
                    userName: [
                        {required: true, message: "用户名称不能为空", trigger: "blur"},
                        {min: 2, max: 12, message: '用户名称长度必须介于 2 和 12 之间', trigger: 'blur'}
                    ],
                    userPhone: [
                        {required: true, message: "用户手机号不能为空", trigger: "blur"},
                        {
                            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                            message: "请输入正确的手机号码",
                            trigger: "blur"
                        }
                    ],
                }
            };
        },
        created() {
            this.getUserList();
        },
        methods: {
            handleBefore(file){
                console.log(file)
            },
            handleSuccess(response, file, fileList){
                console.log(response)
                this.getUserList();
                this.importUser=false;
                this.$message.success('成功导入'+response.data+'条数据！')
            },
            handleChange(file, fileList) {
                this.fileList = fileList.slice(-3);
            },
            importButton(){
                this.fileList=[];
                this.importUser=true;
            },
            /**
             * 用户导入
             * */
            async importUsers() {
                const formData = new FormData();
                formData.append('file', this.selectedFile);

                try {
                    const response = await this.$http.post('/api/users/import', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });
                    this.importResult = `成功导入 ${response.data} 个用户`;
                } catch (error) {
                    this.importResult = '导入失败: ' + error.message;
                }
            },
            /** 导出按钮操作 */
            handleExport() {
                this.$confirm(`确定要导出吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 用户点击"确定"按钮，执行删除操作
                    this.$http.post('user/exportUser', this.ids, {
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        responseType: 'blob' // 指定响应类型为二进制流
                    }).then(res => {
                        // 获取响应数据并进行处理
                        const url = window.URL.createObjectURL(new Blob([res.data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', '用户列表.xlsx'); // 设置下载文件名
                        document.body.appendChild(link);
                        link.click();
                    });
                }).catch(() => {
                    // 用户点击"取消"按钮，什么也不做
                })
            },
            async getUserList() {
                this.loading = true;
                const {data: res} = await this.$http.post('user/getSysUserList', this.queryParams)
                console.log(res)
                this.userList = res.data.children
                this.total = res.data.total
                this.loading = false
            },
            // 取消按钮
            cancel() {
                this.dialogFormVisible = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: 0,
                    userRole: "",
                    userName: "",
                    userPhone: "",
                    status: "0",
                    remark: "",
                };
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.getUserList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                // 查询参数
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    userName: "",
                    userPhone: "",
                },
                    this.getUserList();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id);
                this.single = selection.length != 1;
                this.multiple = !selection.length;
            },
            // 更多操作触发
            handleCommand(command, row) {
                switch (command) {
                    case "handleResetPwd":
                        this.handleResetPwd(row);
                        break;
                    // case "handleAuthRole":
                    //     this.handleAuthRole(row);
                    //     break;
                    default:
                        break;
                }
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.title = "添加用户"
                this.open = true;
            },
            /** 修改按钮操作 */
            async handleUpdate(row) {
                console.log(row)
                this.form = JSON.parse(JSON.stringify(row));
                this.title = "更新用户信息";
                this.dialogFormVisible = true;
            },
            /** 重置密码按钮操作 */
            handleResetPwd(row) {
                this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    closeOnClickModal: false,
                    inputPattern: /^.{6,20}$/,
                    inputErrorMessage: "用户密码长度必须介于 6 和 20 之间"
                }).then(({value}) => {
                    this.$http.get("user/resetPassword", {
                        params: {
                            userId: row.id,
                            password: value
                        }
                    })
                    this.$message.success('密码重置成功！')
                }).catch(() => {
                    this.$message.info('取消重置！')
                });
            },
            /** 提交按钮 */
            async submitForm() {
                await this.$refs["ruleFormRef"].validate(valid => {
                    if (valid) {
                        if (this.form.id != 0) {
                            this.modifyFrom();
                        } else {
                            this.addFromFun();
                        }
                    }
                });
                this.dialogFormVisible = false;
            },
            /**修改用户*/
          /**修改用户*/
          async modifyFrom() {
            const SUCCESS_CODE = 200;
            try {
              const { data: res } = await this.$http.post('user/updateUser', this.form);
              if (res.code === SUCCESS_CODE) {
                this.getUserList();
                this.$message.success('修改成功!');
              } else {
                this.$message.error(res.message || '服务器异常');
              }
            } catch (error) {
              console.error('网络请求出错:', error);
              this.$message.error('网络请求出错，请稍后重试');
            }
          },
            /**
             * 添加用户
             * */
            async addFromFun() {
                const {data: res} = await this.$http.post('user/insertUser', this.form);
                console.log(res)
                if (res.code == 200) {
                    this.$message.success('添加成功')
                    this.getUserList();
                } else if (res.code == 50003) {
                    this.$message.error('用户手机号码已存在!')
                } else {
                    this.$message.error('服务器异常')
                }
            },
            /** 删除按钮操作 */
            async handleDelete(row) {
                this.$confirm('此操作将删除用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    if (row.id) {
                        this.ids = [];
                        this.ids.push(row.id);
                    }
                    console.log(this.ids)
                    const {data: res} = await this.$http.post('user/delUser', this.ids);
                    console.log(res)
                    if (res.code == 200) {
                        this.getUserList();
                        this.$message.success('删除成功！')
                    } else {
                        this.$message.error('服务器异常！')
                    }
                }).catch(() => {
                    this.$message.info('已取消删除！')
                })
            },
            handleSizeChange(newSize) {
                this.queryParams.pageSize = newSize;
                this.getUserList();
            }
            ,
            handleCurrentChange(current) {
                this.queryParams.pageNum = current;
                this.getUserList();
            },
        }
    };
</script>
